import {createRouter, createWebHistory} from 'vue-router';
import Home from '../views/Home.vue'
import NProgress from 'nprogress'
import NotFound from "../views/NotFound.vue";
import store from '../store'
import EventList from "../views/EventList.vue";
import EventList2 from "../views/EventList2.vue";
import EventList3 from "../views/EventList3.vue";
import NetworkIssue from "../views/NetworkIssue.vue";
import BaseForm from "../components/BaseForm.vue";
import BaseVmodel from "../components/cookbook/BaseVmodel.vue";

const routes = [
    {path: '/', name: 'Home', component: Home},
    {path: '/foo', name: 'Foo', component: () => import('../views/Foo.vue')},
    {path: '/cleartimer', name: 'cleartimer', component: () => import('../components/cookbook/ClearTimer.vue')},
    {path: '/keepaliveexample', name: 'keepaliveexample', component: () => import('../components/cookbook/KeepAliveExample.vue')},
    {path: '/basevmodel', name: 'basevmodel', component: BaseVmodel},
    {path: '/basevmodel', name: 'basevmodel', component: BaseVmodel},


    {path: '/event-list', name: 'event-list', component: EventList},
    {path: '/event-list2', component: EventList2},
    {path: '/event-list3', component: EventList3},
    {path: '/base-form', component: BaseForm},
    {path: '/network-issue', component: NetworkIssue},
    {
        path: '/event/:id', name: 'Event', component: () => import('../views/Event.vue'), props: true,
        beforeEnter(routeTo, routeFrom, next) {
            //This runs after the global beforeEach
            store.dispatch('event/fetchEvent', routeTo.params.id).then(() => {
                routeTo.params.id = 5;
                next()
            }).catch(error => {
                if (error.response && error.response.status == 404) {
                    next({name: '404', params: {resource: 'event'}})
                } else {
                    next({name: 'network-issue'})
                }
            })
        }
    },
    {path: '/404', name: '404', component: () => NotFound, props: true},
    {path: '/:pathMatch(.*)*', redirect: {name: '404', params: {resource: 'page'}}},

]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((routeTo, routeFrom, next) => {
    NProgress.start()
    next()
})

router.afterEach(() => {
    NProgress.done()
})
export default router
